home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / platform.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  38KB  |  1,256 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. ''' This module tries to retrieve as much platform-identifying data as
  5.     possible. It makes this information available via function APIs.
  6.  
  7.     If called from the command line, it prints the platform
  8.     information concatenated as single string to stdout. The output
  9.     format is useable as part of a filename.
  10.  
  11. '''
  12. __copyright__ = '\n    Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com\n    Copyright (c) 2000-2008, eGenix.com Software GmbH; mailto:info@egenix.com\n\n    Permission to use, copy, modify, and distribute this software and its\n    documentation for any purpose and without fee or royalty is hereby granted,\n    provided that the above copyright notice appear in all copies and that\n    both that copyright notice and this permission notice appear in\n    supporting documentation or portions thereof, including modifications,\n    that you make.\n\n    EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO\n    THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n    FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,\n    INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING\n    FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n    NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\n    WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !\n\n'
  13. __version__ = '1.0.6'
  14. import sys
  15. import string
  16. import os
  17. import re
  18. _libc_search = re.compile('(__libc_init)|(GLIBC_([0-9.]+))|(libc(_\\w+)?\\.so(?:\\.(\\d[0-9.]*))?)')
  19.  
  20. def libc_ver(executable = sys.executable, lib = '', version = '', chunksize = 2048):
  21.     ''' Tries to determine the libc version that the file executable
  22.         (which defaults to the Python interpreter) is linked against.
  23.  
  24.         Returns a tuple of strings (lib,version) which default to the
  25.         given parameters in case the lookup fails.
  26.  
  27.         Note that the function has intimate knowledge of how different
  28.         libc versions add symbols to the executable and thus is probably
  29.         only useable for executables compiled using gcc.
  30.  
  31.         The file is read and scanned in chunks of chunksize bytes.
  32.  
  33.     '''
  34.     if hasattr(os.path, 'realpath'):
  35.         executable = os.path.realpath(executable)
  36.     
  37.     f = open(executable, 'rb')
  38.     binary = f.read(chunksize)
  39.     pos = 0
  40.     while None:
  41.         m = _libc_search.search(binary, pos)
  42.         if not m:
  43.             binary = f.read(chunksize)
  44.             if not binary:
  45.                 break
  46.             
  47.             pos = 0
  48.             continue
  49.         
  50.         (libcinit, glibc, glibcversion, so, threads, soversion) = m.groups()
  51.         if libcinit and not lib:
  52.             lib = 'libc'
  53.         elif glibc:
  54.             if lib != 'glibc':
  55.                 lib = 'glibc'
  56.                 version = glibcversion
  57.             elif glibcversion > version:
  58.                 version = glibcversion
  59.             
  60.         elif so:
  61.             if lib != 'glibc':
  62.                 lib = 'libc'
  63.                 if soversion > version:
  64.                     version = soversion
  65.                 
  66.                 if threads and version[-len(threads):] != threads:
  67.                     version = version + threads
  68.                 
  69.             
  70.         
  71.         pos = m.end()
  72.         continue
  73.         return (lib, version)
  74.  
  75.  
  76. def _dist_try_harder(distname, version, id):
  77.     ''' Tries some special tricks to get the distribution
  78.         information in case the default method fails.
  79.  
  80.         Currently supports older SuSE Linux, Caldera OpenLinux and
  81.         Slackware Linux distributions.
  82.  
  83.     '''
  84.     if os.path.exists('/var/adm/inst-log/info'):
  85.         info = open('/var/adm/inst-log/info').readlines()
  86.         distname = 'SuSE'
  87.         for line in info:
  88.             tv = string.split(line)
  89.             if len(tv) == 2:
  90.                 (tag, value) = tv
  91.             
  92.             if tag == 'MIN_DIST_VERSION':
  93.                 version = string.strip(value)
  94.                 continue
  95.             len(tv) == 2
  96.             if tag == 'DIST_IDENT':
  97.                 values = string.split(value, '-')
  98.                 id = values[2]
  99.                 continue
  100.         
  101.         return (distname, version, id)
  102.     if os.path.isdir('/usr/lib/setup'):
  103.         verfiles = os.listdir('/usr/lib/setup')
  104.         for n in range(len(verfiles) - 1, -1, -1):
  105.             if verfiles[n][:14] != 'slack-version-':
  106.                 del verfiles[n]
  107.                 continue
  108.             None if os.path.exists('/etc/.installed') else os.path.exists('/var/adm/inst-log/info')
  109.         
  110.         if verfiles:
  111.             verfiles.sort()
  112.             distname = 'slackware'
  113.             version = verfiles[-1][14:]
  114.             return (distname, version, id)
  115.     
  116.     return (distname, version, id)
  117.  
  118. _release_filename = re.compile('(\\w+)[-_](release|version)')
  119. _lsb_release_version = re.compile('(.+) release ([\\d.]+)[^(]*(?:\\((.+)\\))?')
  120. _release_version = re.compile('([^0-9]+)(?: release )?([\\d.]+)[^(]*(?:\\((.+)\\))?')
  121. _supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos', 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', 'UnitedLinux', 'turbolinux')
  122.  
  123. def _parse_release_file(firstline):
  124.     m = _lsb_release_version.match(firstline)
  125.     if m is not None:
  126.         return tuple(m.groups())
  127.     m = _release_version.match(firstline)
  128.     if m is not None:
  129.         return tuple(m.groups())
  130.     l = string.split(string.strip(firstline))
  131.     return ('', version, id)
  132.  
  133.  
  134. def _test_parse_release_file():
  135.     for input, output in ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))('CentOS release 4', ('CentOS', '4', None))('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')):
  136.         parsed = _parse_release_file(input)
  137.         if parsed != output:
  138.             print (input, parsed)
  139.             continue
  140.     
  141.  
  142. _distributor_id_file_re = re.compile('(?:DISTRIB_ID\\s*=)\\s*(.*)', re.I)
  143. _release_file_re = re.compile('(?:DISTRIB_RELEASE\\s*=)\\s*(.*)', re.I)
  144. _codename_file_re = re.compile('(?:DISTRIB_CODENAME\\s*=)\\s*(.*)', re.I)
  145.  
  146. def linux_distribution(distname = '', version = '', id = '', supported_dists = _supported_dists, full_distribution_name = 1):
  147.     ''' Tries to determine the name of the Linux OS distribution name.
  148.  
  149.         The function first looks for a distribution release file in
  150.         /etc and then reverts to _dist_try_harder() in case no
  151.         suitable files are found.
  152.  
  153.         supported_dists may be given to define the set of Linux
  154.         distributions to look for. It defaults to a list of currently
  155.         supported Linux distributions identified by their release file
  156.         name.
  157.  
  158.         If full_distribution_name is true (default), the full
  159.         distribution read from the OS is returned. Otherwise the short
  160.         name taken from supported_dists is used.
  161.  
  162.         Returns a tuple (distname,version,id) which default to the
  163.         args given as parameters.
  164.  
  165.     '''
  166.     
  167.     try:
  168.         etclsbrel = open('/etc/lsb-release', 'rU')
  169.         for line in etclsbrel:
  170.             m = _distributor_id_file_re.search(line)
  171.             if m:
  172.                 _u_distname = m.group(1).strip()
  173.             
  174.             m = _release_file_re.search(line)
  175.             if m:
  176.                 _u_version = m.group(1).strip()
  177.             
  178.             m = _codename_file_re.search(line)
  179.             if m:
  180.                 _u_id = m.group(1).strip()
  181.                 continue
  182.         
  183.         if _u_distname and _u_version:
  184.             return (_u_distname, _u_version, _u_id)
  185.     except (EnvironmentError, UnboundLocalError):
  186.         pass
  187.  
  188.     
  189.     try:
  190.         etc = os.listdir('/etc')
  191.     except os.error:
  192.         return (distname, version, id)
  193.  
  194.     etc.sort()
  195.     for file in etc:
  196.         m = _release_filename.match(file)
  197.         if m is not None:
  198.             (_distname, dummy) = m.groups()
  199.             if _distname in supported_dists:
  200.                 distname = _distname
  201.                 break
  202.             
  203.         _distname in supported_dists
  204.     else:
  205.         return _dist_try_harder(distname, version, id)
  206.     f = None('/etc/' + file, 'r')
  207.     firstline = f.readline()
  208.     f.close()
  209.     (_distname, _version, _id) = _parse_release_file(firstline)
  210.     if _distname and full_distribution_name:
  211.         distname = _distname
  212.     
  213.     if _version:
  214.         version = _version
  215.     
  216.     if _id:
  217.         id = _id
  218.     
  219.     return (distname, version, id)
  220.  
  221.  
  222. def dist(distname = '', version = '', id = '', supported_dists = _supported_dists):
  223.     ''' Tries to determine the name of the Linux OS distribution name.
  224.  
  225.         The function first looks for a distribution release file in
  226.         /etc and then reverts to _dist_try_harder() in case no
  227.         suitable files are found.
  228.  
  229.         Returns a tuple (distname,version,id) which default to the
  230.         args given as parameters.
  231.  
  232.     '''
  233.     return linux_distribution(distname, version, id, supported_dists = supported_dists, full_distribution_name = 0)
  234.  
  235.  
  236. class _popen:
  237.     """ Fairly portable (alternative) popen implementation.
  238.  
  239.         This is mostly needed in case os.popen() is not available, or
  240.         doesn't work as advertised, e.g. in Win9X GUI programs like
  241.         PythonWin or IDLE.
  242.  
  243.         Writing to the pipe is currently not supported.
  244.  
  245.     """
  246.     tmpfile = ''
  247.     pipe = None
  248.     bufsize = None
  249.     mode = 'r'
  250.     
  251.     def __init__(self, cmd, mode = 'r', bufsize = None):
  252.         if mode != 'r':
  253.             raise ValueError, 'popen()-emulation only supports read mode'
  254.         mode != 'r'
  255.         import tempfile as tempfile
  256.         self.tmpfile = tmpfile = tempfile.mktemp()
  257.         os.system(cmd + ' > %s' % tmpfile)
  258.         self.pipe = open(tmpfile, 'rb')
  259.         self.bufsize = bufsize
  260.         self.mode = mode
  261.  
  262.     
  263.     def read(self):
  264.         return self.pipe.read()
  265.  
  266.     
  267.     def readlines(self):
  268.         if self.bufsize is not None:
  269.             return self.pipe.readlines()
  270.  
  271.     
  272.     def close(self, remove = os.unlink, error = os.error):
  273.         if self.pipe:
  274.             rc = self.pipe.close()
  275.         else:
  276.             rc = 255
  277.         if self.tmpfile:
  278.             
  279.             try:
  280.                 remove(self.tmpfile)
  281.             except error:
  282.                 pass
  283.             except:
  284.                 None<EXCEPTION MATCH>error
  285.             
  286.  
  287.         None<EXCEPTION MATCH>error
  288.         return rc
  289.  
  290.     __del__ = close
  291.  
  292.  
  293. def popen(cmd, mode = 'r', bufsize = None):
  294.     ''' Portable popen() interface.
  295.     '''
  296.     popen = None
  297.     if os.environ.get('OS', '') == 'Windows_NT':
  298.         
  299.         try:
  300.             import win32pipe as win32pipe
  301.         except ImportError:
  302.             pass
  303.  
  304.         popen = win32pipe.popen
  305.     
  306.     if popen is None:
  307.         if hasattr(os, 'popen'):
  308.             popen = os.popen
  309.             if sys.platform == 'win32':
  310.                 
  311.                 try:
  312.                     popen('')
  313.                 except os.error:
  314.                     popen = _popen
  315.                 except:
  316.                     None<EXCEPTION MATCH>os.error
  317.                 
  318.  
  319.             None<EXCEPTION MATCH>os.error
  320.         else:
  321.             popen = _popen
  322.     
  323.     if bufsize is None:
  324.         return popen(cmd, mode)
  325.     return popen(cmd, mode, bufsize)
  326.  
  327.  
  328. def _norm_version(version, build = ''):
  329.     ''' Normalize the version and build strings and return a single
  330.         version string using the format major.minor.build (or patchlevel).
  331.     '''
  332.     l = string.split(version, '.')
  333.     if build:
  334.         l.append(build)
  335.     
  336.     
  337.     try:
  338.         ints = map(int, l)
  339.     except ValueError:
  340.         strings = l
  341.  
  342.     strings = map(str, ints)
  343.     version = string.join(strings[:3], '.')
  344.     return version
  345.  
  346. _ver_output = re.compile('(?:([\\w ]+) ([\\w.]+) .*Version ([\\d.]+))')
  347.  
  348. def _syscmd_ver(system = '', release = '', version = '', supported_platforms = ('win32', 'win16', 'dos', 'os2')):
  349.     ''' Tries to figure out the OS version used and returns
  350.         a tuple (system,release,version).
  351.  
  352.         It uses the "ver" shell command for this which is known
  353.         to exists on Windows, DOS and OS/2. XXX Others too ?
  354.  
  355.         In case this fails, the given parameters are used as
  356.         defaults.
  357.  
  358.     '''
  359.     return (system, release, version)
  360.  
  361.  
  362. def _win32_getvalue(key, name, default = ''):
  363.     ''' Read a value for name from the registry key.
  364.  
  365.         In case this fails, default is returned.
  366.  
  367.     '''
  368.     
  369.     try:
  370.         RegQueryValueEx = RegQueryValueEx
  371.         import win32api
  372.     except ImportError:
  373.         import _winreg as _winreg
  374.         RegQueryValueEx = _winreg.QueryValueEx
  375.  
  376.     
  377.     try:
  378.         return RegQueryValueEx(key, name)
  379.     except:
  380.         return default
  381.  
  382.  
  383.  
  384. def win32_ver(release = '', version = '', csd = '', ptype = ''):
  385.     """ Get additional version information from the Windows Registry
  386.         and return a tuple (version,csd,ptype) referring to version
  387.         number, CSD level and OS type (multi/single
  388.         processor).
  389.  
  390.         As a hint: ptype returns 'Uniprocessor Free' on single
  391.         processor NT machines and 'Multiprocessor Free' on multi
  392.         processor machines. The 'Free' refers to the OS version being
  393.         free of debugging code. It could also state 'Checked' which
  394.         means the OS version uses debugging code, i.e. code that
  395.         checks arguments, ranges, etc. (Thomas Heller).
  396.  
  397.         Note: this function works best with Mark Hammond's win32
  398.         package installed, but also on Python 2.3 and later. It
  399.         obviously only runs on Win32 compatible platforms.
  400.  
  401.     """
  402.     
  403.     try:
  404.         import win32api
  405.         RegQueryValueEx = RegQueryValueEx
  406.         RegOpenKeyEx = RegOpenKeyEx
  407.         RegCloseKey = RegCloseKey
  408.         GetVersionEx = GetVersionEx
  409.         import win32api
  410.         HKEY_LOCAL_MACHINE = HKEY_LOCAL_MACHINE
  411.         VER_PLATFORM_WIN32_NT = VER_PLATFORM_WIN32_NT
  412.         VER_PLATFORM_WIN32_WINDOWS = VER_PLATFORM_WIN32_WINDOWS
  413.         VER_NT_WORKSTATION = VER_NT_WORKSTATION
  414.         import win32con
  415.     except ImportError:
  416.         
  417.         try:
  418.             sys.getwindowsversion
  419.         except AttributeError:
  420.             return (release, version, csd, ptype)
  421.  
  422.         import _winreg
  423.         GetVersionEx = sys.getwindowsversion
  424.         RegQueryValueEx = _winreg.QueryValueEx
  425.         RegOpenKeyEx = _winreg.OpenKeyEx
  426.         RegCloseKey = _winreg.CloseKey
  427.         HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
  428.         VER_PLATFORM_WIN32_WINDOWS = 1
  429.         VER_PLATFORM_WIN32_NT = 2
  430.         VER_NT_WORKSTATION = 1
  431.  
  432.     (maj, min, buildno, plat, csd) = GetVersionEx()
  433.     version = '%i.%i.%i' % (maj, min, buildno & 65535)
  434.     if csd[:13] == 'Service Pack ':
  435.         csd = 'SP' + csd[13:]
  436.     
  437.     if plat == VER_PLATFORM_WIN32_WINDOWS:
  438.         regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
  439.         if maj == 4:
  440.             if min == 0:
  441.                 release = '95'
  442.             elif min == 10:
  443.                 release = '98'
  444.             elif min == 90:
  445.                 release = 'Me'
  446.             else:
  447.                 release = 'postMe'
  448.         elif maj == 5:
  449.             release = '2000'
  450.         
  451.     elif plat == VER_PLATFORM_WIN32_NT:
  452.         regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
  453.         if maj <= 4:
  454.             release = 'NT'
  455.         elif maj == 5:
  456.             if min == 0:
  457.                 release = '2000'
  458.             elif min == 1:
  459.                 release = 'XP'
  460.             elif min == 2:
  461.                 release = '2003Server'
  462.             else:
  463.                 release = 'post2003'
  464.         elif maj == 6:
  465.             if min == 0:
  466.                 
  467.                 try:
  468.                     productType = GetVersionEx(1)[8]
  469.                 except TypeError:
  470.                     release = 'Vista'
  471.  
  472.                 if productType == VER_NT_WORKSTATION:
  473.                     release = 'Vista'
  474.                 else:
  475.                     release = '2008Server'
  476.             else:
  477.                 release = 'post2008Server'
  478.         
  479.     elif not release:
  480.         release = '%i.%i' % (maj, min)
  481.     
  482.     return (release, version, csd, ptype)
  483.     
  484.     try:
  485.         keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  486.         RegQueryValueEx(keyCurVer, 'SystemRoot')
  487.     except:
  488.         return (release, version, csd, ptype)
  489.  
  490.     build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('', 1))[0]
  491.     ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype, 1))[0]
  492.     version = _norm_version(version, build)
  493.     RegCloseKey(keyCurVer)
  494.     return (release, version, csd, ptype)
  495.  
  496.  
  497. def _mac_ver_lookup(selectors, default = None):
  498.     gestalt = gestalt
  499.     import gestalt
  500.     import MacOS as MacOS
  501.     l = []
  502.     append = l.append
  503.     for selector in selectors:
  504.         
  505.         try:
  506.             append(gestalt(selector))
  507.         continue
  508.         except (RuntimeError, MacOS.Error):
  509.             append(default)
  510.             continue
  511.         
  512.  
  513.     
  514.     return l
  515.  
  516.  
  517. def _bcd2str(bcd):
  518.     return hex(bcd)[2:]
  519.  
  520.  
  521. def mac_ver(release = '', versioninfo = ('', '', ''), machine = ''):
  522.     """ Get MacOS version information and return it as tuple (release,
  523.         versioninfo, machine) with versioninfo being a tuple (version,
  524.         dev_stage, non_release_version).
  525.  
  526.         Entries which cannot be determined are set to the paramter values
  527.         which default to ''. All tuple entries are strings.
  528.  
  529.         Thanks to Mark R. Levinson for mailing documentation links and
  530.         code examples for this function. Documentation for the
  531.         gestalt() API is available online at:
  532.  
  533.            http://www.rgaros.nl/gestalt/
  534.  
  535.     """
  536.     
  537.     try:
  538.         import gestalt
  539.         import MacOS
  540.     except ImportError:
  541.         return (release, versioninfo, machine)
  542.  
  543.     (sysv, sysu, sysa) = _mac_ver_lookup(('sysv', 'sysu', 'sysa'))
  544.     if sysv:
  545.         major = (sysv & 65280) >> 8
  546.         minor = (sysv & 240) >> 4
  547.         patch = sysv & 15
  548.         if (major, minor) >= (10, 4):
  549.             (major, minor, patch) = _mac_ver_lookup(('sys1', 'sys2', 'sys3'))
  550.             release = '%i.%i.%i' % (major, minor, patch)
  551.         else:
  552.             release = '%s.%i.%i' % (_bcd2str(major), minor, patch)
  553.     
  554.     if sysu:
  555.         major = int((sysu & 0xFF000000L) >> 24)
  556.         minor = (sysu & 15728640) >> 20
  557.         bugfix = (sysu & 983040) >> 16
  558.         stage = (sysu & 65280) >> 8
  559.         nonrel = sysu & 255
  560.         version = '%s.%i.%i' % (_bcd2str(major), minor, bugfix)
  561.         nonrel = _bcd2str(nonrel)
  562.         stage = {
  563.             32: 'development',
  564.             64: 'alpha',
  565.             96: 'beta',
  566.             128: 'final' }.get(stage, '')
  567.         versioninfo = (version, stage, nonrel)
  568.     
  569.     if sysa:
  570.         machine = {
  571.             1: '68k',
  572.             2: 'PowerPC',
  573.             10: 'i386' }.get(sysa, '')
  574.     
  575.     return (release, versioninfo, machine)
  576.  
  577.  
  578. def _java_getprop(name, default):
  579.     System = System
  580.     import java.lang
  581.     
  582.     try:
  583.         value = System.getProperty(name)
  584.         if value is None:
  585.             return default
  586.         return value
  587.     except AttributeError:
  588.         return default
  589.  
  590.  
  591.  
  592. def java_ver(release = '', vendor = '', vminfo = ('', '', ''), osinfo = ('', '', '')):
  593.     """ Version interface for Jython.
  594.  
  595.         Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  596.         a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  597.         tuple (os_name,os_version,os_arch).
  598.  
  599.         Values which cannot be determined are set to the defaults
  600.         given as parameters (which all default to '').
  601.  
  602.     """
  603.     
  604.     try:
  605.         import java.lang as java
  606.     except ImportError:
  607.         return (release, vendor, vminfo, osinfo)
  608.  
  609.     vendor = _java_getprop('java.vendor', vendor)
  610.     release = _java_getprop('java.version', release)
  611.     (vm_name, vm_release, vm_vendor) = vminfo
  612.     vm_name = _java_getprop('java.vm.name', vm_name)
  613.     vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  614.     vm_release = _java_getprop('java.vm.version', vm_release)
  615.     vminfo = (vm_name, vm_release, vm_vendor)
  616.     (os_name, os_version, os_arch) = osinfo
  617.     os_arch = _java_getprop('java.os.arch', os_arch)
  618.     os_name = _java_getprop('java.os.name', os_name)
  619.     os_version = _java_getprop('java.os.version', os_version)
  620.     osinfo = (os_name, os_version, os_arch)
  621.     return (release, vendor, vminfo, osinfo)
  622.  
  623.  
  624. def system_alias(system, release, version):
  625.     ''' Returns (system,release,version) aliased to common
  626.         marketing names used for some systems.
  627.  
  628.         It also does some reordering of the information in some cases
  629.         where it would otherwise cause confusion.
  630.  
  631.     '''
  632.     if system == 'Rhapsody':
  633.         return ('MacOS X Server', system + release, version)
  634.     if system == 'SunOS':
  635.         if release < '5':
  636.             return (system, release, version)
  637.         l = string.split(release, '.')
  638.         if release < '6':
  639.             system = 'Solaris'
  640.         else:
  641.             system = 'Solaris'
  642.     elif system == 'IRIX64':
  643.         system = 'IRIX'
  644.         if version:
  645.             version = version + ' (64bit)'
  646.         else:
  647.             version = '64bit'
  648.     elif system in ('win32', 'win16'):
  649.         system = 'Windows'
  650.     
  651.     return (system, release, version)
  652.  
  653.  
  654. def _platform(*args):
  655.     ''' Helper to format the platform string in a filename
  656.         compatible format e.g. "system-version-machine".
  657.     '''
  658.     platform = string.join(map(string.strip, filter(len, args)), '-')
  659.     replace = string.replace
  660.     platform = replace(platform, ' ', '_')
  661.     platform = replace(platform, '/', '-')
  662.     platform = replace(platform, '\\', '-')
  663.     platform = replace(platform, ':', '-')
  664.     platform = replace(platform, ';', '-')
  665.     platform = replace(platform, '"', '-')
  666.     platform = replace(platform, '(', '-')
  667.     platform = replace(platform, ')', '-')
  668.     platform = replace(platform, 'unknown', '')
  669.     while None:
  670.         cleaned = replace(platform, '--', '-')
  671.         if cleaned == platform:
  672.             break
  673.         
  674.         platform = cleaned
  675.         continue
  676.         while platform[-1] == '-':
  677.             platform = platform[:-1]
  678.         return platform
  679.  
  680.  
  681. def _node(default = ''):
  682.     ''' Helper to determine the node name of this machine.
  683.     '''
  684.     
  685.     try:
  686.         import socket as socket
  687.     except ImportError:
  688.         return default
  689.  
  690.     
  691.     try:
  692.         return socket.gethostname()
  693.     except socket.error:
  694.         return default
  695.  
  696.  
  697. if not hasattr(os.path, 'abspath'):
  698.     
  699.     def _abspath(path, isabs = os.path.isabs, join = os.path.join, getcwd = os.getcwd, normpath = os.path.normpath):
  700.         if not isabs(path):
  701.             path = join(getcwd(), path)
  702.         
  703.         return normpath(path)
  704.  
  705. else:
  706.     _abspath = os.path.abspath
  707.  
  708. def _follow_symlinks(filepath):
  709.     ''' In case filepath is a symlink, follow it until a
  710.         real file is reached.
  711.     '''
  712.     filepath = _abspath(filepath)
  713.     while os.path.islink(filepath):
  714.         filepath = os.path.normpath(os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
  715.     return filepath
  716.  
  717.  
  718. def _syscmd_uname(option, default = ''):
  719.     """ Interface to the system's uname command.
  720.     """
  721.     if sys.platform in ('dos', 'win32', 'win16', 'os2'):
  722.         return default
  723.     
  724.     try:
  725.         f = os.popen('uname %s 2> /dev/null' % option)
  726.     except (AttributeError, os.error):
  727.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  728.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  729.         return default
  730.  
  731.     output = string.strip(f.read())
  732.     rc = f.close()
  733.     if not output or rc:
  734.         return default
  735.     return output
  736.  
  737.  
  738. def _syscmd_file(target, default = ''):
  739.     """ Interface to the system's file command.
  740.  
  741.         The function uses the -b option of the file command to have it
  742.         ommit the filename in its output and if possible the -L option
  743.         to have the command follow symlinks. It returns default in
  744.         case the command should fail.
  745.  
  746.     """
  747.     if sys.platform in ('dos', 'win32', 'win16', 'os2'):
  748.         return default
  749.     target = _follow_symlinks(target)
  750.     
  751.     try:
  752.         f = os.popen('file "%s" 2> /dev/null' % target)
  753.     except (AttributeError, os.error):
  754.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  755.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  756.         return default
  757.  
  758.     output = string.strip(f.read())
  759.     rc = f.close()
  760.     if not output or rc:
  761.         return default
  762.     return output
  763.  
  764. _default_architecture = {
  765.     'win32': ('', 'WindowsPE'),
  766.     'win16': ('', 'Windows'),
  767.     'dos': ('', 'MSDOS') }
  768. _architecture_split = re.compile('[\\s,]').split
  769.  
  770. def architecture(executable = sys.executable, bits = '', linkage = ''):
  771.     ''' Queries the given executable (defaults to the Python interpreter
  772.         binary) for various architecture information.
  773.  
  774.         Returns a tuple (bits,linkage) which contains information about
  775.         the bit architecture and the linkage format used for the
  776.         executable. Both values are returned as strings.
  777.  
  778.         Values that cannot be determined are returned as given by the
  779.         parameter presets. If bits is given as \'\', the sizeof(pointer)
  780.         (or sizeof(long) on Python version < 1.5.2) is used as
  781.         indicator for the supported pointer size.
  782.  
  783.         The function relies on the system\'s "file" command to do the
  784.         actual work. This is available on most if not all Unix
  785.         platforms. On some non-Unix platforms where the "file" command
  786.         does not exist and the executable is set to the Python interpreter
  787.         binary defaults from _default_architecture are used.
  788.  
  789.     '''
  790.     if not bits:
  791.         import struct as struct
  792.         
  793.         try:
  794.             size = struct.calcsize('P')
  795.         except struct.error:
  796.             size = struct.calcsize('l')
  797.  
  798.         bits = str(size * 8) + 'bit'
  799.     
  800.     if executable:
  801.         output = _syscmd_file(executable, '')
  802.     else:
  803.         output = ''
  804.     if not output and executable == sys.executable:
  805.         if _default_architecture.has_key(sys.platform):
  806.             (b, l) = _default_architecture[sys.platform]
  807.             if b:
  808.                 bits = b
  809.             
  810.             if l:
  811.                 linkage = l
  812.             
  813.         
  814.         return (bits, linkage)
  815.     fileout = _architecture_split(output)[1:]
  816.     if 'executable' not in fileout:
  817.         return (bits, linkage)
  818.     if '32-bit' in fileout:
  819.         bits = '32bit'
  820.     elif 'N32' in fileout:
  821.         bits = 'n32bit'
  822.     elif '64-bit' in fileout:
  823.         bits = '64bit'
  824.     
  825.     if 'ELF' in fileout:
  826.         linkage = 'ELF'
  827.     elif 'PE' in fileout:
  828.         if 'Windows' in fileout:
  829.             linkage = 'WindowsPE'
  830.         else:
  831.             linkage = 'PE'
  832.     elif 'COFF' in fileout:
  833.         linkage = 'COFF'
  834.     elif 'MS-DOS' in fileout:
  835.         linkage = 'MSDOS'
  836.     
  837.     return (bits, linkage)
  838.  
  839. _uname_cache = None
  840.  
  841. def uname():
  842.     """ Fairly portable uname interface. Returns a tuple
  843.         of strings (system,node,release,version,machine,processor)
  844.         identifying the underlying platform.
  845.  
  846.         Note that unlike the os.uname function this also returns
  847.         possible processor information as an additional tuple entry.
  848.  
  849.         Entries which cannot be determined are set to ''.
  850.  
  851.     """
  852.     global _uname_cache
  853.     no_os_uname = 0
  854.     if _uname_cache is not None:
  855.         return _uname_cache
  856.     processor = ''
  857.     
  858.     try:
  859.         (system, node, release, version, machine) = os.uname()
  860.     except AttributeError:
  861.         _uname_cache is not None
  862.         _uname_cache is not None
  863.         no_os_uname = 1
  864.     except:
  865.         _uname_cache is not None
  866.  
  867.     if no_os_uname or not filter(None, (system, node, release, version, machine)):
  868.         if no_os_uname:
  869.             system = sys.platform
  870.             release = ''
  871.             version = ''
  872.             node = _node()
  873.             machine = ''
  874.         
  875.         use_syscmd_ver = 1
  876.         if system == 'win32':
  877.             (release, version, csd, ptype) = win32_ver()
  878.             if release and version:
  879.                 use_syscmd_ver = 0
  880.             
  881.             if not machine:
  882.                 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  883.             
  884.             if not processor:
  885.                 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  886.             
  887.         
  888.         if use_syscmd_ver:
  889.             (system, release, version) = _syscmd_ver(system)
  890.             if system == 'Microsoft Windows':
  891.                 system = 'Windows'
  892.             elif system == 'Microsoft' and release == 'Windows':
  893.                 system = 'Windows'
  894.                 if '6.0' == version[:3]:
  895.                     release = 'Vista'
  896.                 else:
  897.                     release = ''
  898.             
  899.         
  900.         if system in ('win32', 'win16'):
  901.             if not version:
  902.                 if system == 'win32':
  903.                     version = '32bit'
  904.                 else:
  905.                     version = '16bit'
  906.             
  907.             system = 'Windows'
  908.         elif system[:4] == 'java':
  909.             (release, vendor, vminfo, osinfo) = java_ver()
  910.             system = 'Java'
  911.             version = string.join(vminfo, ', ')
  912.             if not version:
  913.                 version = vendor
  914.             
  915.         elif os.name == 'mac':
  916.             (version, stage, nonrel) = (release,)
  917.             machine = mac_ver()
  918.             system = 'MacOS'
  919.         
  920.     
  921.     if system == 'OpenVMS':
  922.         if not release or release == '0':
  923.             release = version
  924.             version = ''
  925.         
  926.         
  927.         try:
  928.             import vms_lib as vms_lib
  929.         except ImportError:
  930.             pass
  931.  
  932.         (csid, cpu_number) = vms_lib.getsyi('SYI$_CPU', 0)
  933.         if cpu_number >= 128:
  934.             processor = 'Alpha'
  935.         else:
  936.             processor = 'VAX'
  937.     
  938.     if not processor:
  939.         processor = _syscmd_uname('-p', '')
  940.     
  941.     if system == 'unknown':
  942.         system = ''
  943.     
  944.     if node == 'unknown':
  945.         node = ''
  946.     
  947.     if release == 'unknown':
  948.         release = ''
  949.     
  950.     if version == 'unknown':
  951.         version = ''
  952.     
  953.     if machine == 'unknown':
  954.         machine = ''
  955.     
  956.     if processor == 'unknown':
  957.         processor = ''
  958.     
  959.     if system == 'Microsoft' and release == 'Windows':
  960.         system = 'Windows'
  961.         release = 'Vista'
  962.     
  963.     _uname_cache = (system, node, release, version, machine, processor)
  964.     return _uname_cache
  965.  
  966.  
  967. def system():
  968.     """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  969.  
  970.         An empty string is returned if the value cannot be determined.
  971.  
  972.     """
  973.     return uname()[0]
  974.  
  975.  
  976. def node():
  977.     """ Returns the computer's network name (which may not be fully
  978.         qualified)
  979.  
  980.         An empty string is returned if the value cannot be determined.
  981.  
  982.     """
  983.     return uname()[1]
  984.  
  985.  
  986. def release():
  987.     """ Returns the system's release, e.g. '2.2.0' or 'NT'
  988.  
  989.         An empty string is returned if the value cannot be determined.
  990.  
  991.     """
  992.     return uname()[2]
  993.  
  994.  
  995. def version():
  996.     """ Returns the system's release version, e.g. '#3 on degas'
  997.  
  998.         An empty string is returned if the value cannot be determined.
  999.  
  1000.     """
  1001.     return uname()[3]
  1002.  
  1003.  
  1004. def machine():
  1005.     """ Returns the machine type, e.g. 'i386'
  1006.  
  1007.         An empty string is returned if the value cannot be determined.
  1008.  
  1009.     """
  1010.     return uname()[4]
  1011.  
  1012.  
  1013. def processor():
  1014.     """ Returns the (true) processor name, e.g. 'amdk6'
  1015.  
  1016.         An empty string is returned if the value cannot be
  1017.         determined. Note that many platforms do not provide this
  1018.         information or simply return the same value as for machine(),
  1019.         e.g.  NetBSD does this.
  1020.  
  1021.     """
  1022.     return uname()[5]
  1023.  
  1024. _sys_version_parser = re.compile('([\\w.+]+)\\s*\\(#?([^,]+),\\s*([\\w ]+),\\s*([\\w :]+)\\)\\s*\\[([^\\]]+)\\]?')
  1025. _jython_sys_version_parser = re.compile('([\\d\\.]+)')
  1026. _ironpython_sys_version_parser = re.compile('IronPython\\s*([\\d\\.]+)(?: \\(([\\d\\.]+)\\))? on (.NET [\\d\\.]+)')
  1027. _sys_version_cache = { }
  1028.  
  1029. def _sys_version(sys_version = None):
  1030.     """ Returns a parsed version of Python's sys.version as tuple
  1031.         (name, version, branch, revision, buildno, builddate, compiler)
  1032.         referring to the Python implementation name, version, branch,
  1033.         revision, build number, build date/time as string and the compiler
  1034.         identification string.
  1035.  
  1036.         Note that unlike the Python sys.version, the returned value
  1037.         for the Python version will always include the patchlevel (it
  1038.         defaults to '.0').
  1039.  
  1040.         The function returns empty strings for tuple entries that
  1041.         cannot be determined.
  1042.  
  1043.         sys_version may be given to parse an alternative version
  1044.         string, e.g. if the version was read from a different Python
  1045.         interpreter.
  1046.  
  1047.     """
  1048.     if sys_version is None:
  1049.         sys_version = sys.version
  1050.     
  1051.     result = _sys_version_cache.get(sys_version, None)
  1052.     if result is not None:
  1053.         return result
  1054.     if sys_version[:10] == 'IronPython':
  1055.         name = 'IronPython'
  1056.         match = _ironpython_sys_version_parser.match(sys_version)
  1057.         if match is None:
  1058.             raise ValueError('failed to parse IronPython sys.version: %s' % repr(sys_version))
  1059.         match is None
  1060.         (version, alt_version, compiler) = match.groups()
  1061.         branch = ''
  1062.         revision = ''
  1063.         buildno = ''
  1064.         builddate = ''
  1065.     elif sys.platform[:4] == 'java':
  1066.         name = 'Jython'
  1067.         match = _jython_sys_version_parser.match(sys_version)
  1068.         if match is None:
  1069.             raise ValueError('failed to parse Jython sys.version: %s' % repr(sys_version))
  1070.         match is None
  1071.         (version,) = match.groups()
  1072.         branch = ''
  1073.         revision = ''
  1074.         compiler = sys.platform
  1075.         buildno = ''
  1076.         builddate = ''
  1077.     else:
  1078.         match = _sys_version_parser.match(sys_version)
  1079.         if match is None:
  1080.             raise ValueError('failed to parse CPython sys.version: %s' % repr(sys_version))
  1081.         match is None
  1082.         (version, buildno, builddate, buildtime, compiler) = match.groups()
  1083.         if hasattr(sys, 'subversion'):
  1084.             (name, branch, revision) = sys.subversion
  1085.         else:
  1086.             name = 'CPython'
  1087.             branch = ''
  1088.             revision = ''
  1089.         builddate = builddate + ' ' + buildtime
  1090.     l = string.split(version, '.')
  1091.     if len(l) == 2:
  1092.         l.append('0')
  1093.         version = string.join(l, '.')
  1094.     
  1095.     result = (name, version, branch, revision, buildno, builddate, compiler)
  1096.     _sys_version_cache[sys_version] = result
  1097.     return result
  1098.  
  1099.  
  1100. def _test_sys_version():
  1101.     _sys_version_cache.clear()
  1102.     for input, output in (('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]', ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')), ('IronPython 1.0.60816 on .NET 2.0.50727.42', ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')), ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42', ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42'))):
  1103.         parsed = _sys_version(input)
  1104.         if parsed != output:
  1105.             print (input, parsed)
  1106.             continue
  1107.     
  1108.  
  1109.  
  1110. def python_implementation():
  1111.     """ Returns a string identifying the Python implementation.
  1112.  
  1113.         Currently, the following implementations are identified:
  1114.         'CPython' (C implementation of Python),
  1115.         'IronPython' (.NET implementation of Python),
  1116.         'Jython' (Java implementation of Python).
  1117.  
  1118.     """
  1119.     return _sys_version()[0]
  1120.  
  1121.  
  1122. def python_version():
  1123.     """ Returns the Python version as string 'major.minor.patchlevel'
  1124.  
  1125.         Note that unlike the Python sys.version, the returned value
  1126.         will always include the patchlevel (it defaults to 0).
  1127.  
  1128.     """
  1129.     return _sys_version()[1]
  1130.  
  1131.  
  1132. def python_version_tuple():
  1133.     ''' Returns the Python version as tuple (major, minor, patchlevel)
  1134.         of strings.
  1135.  
  1136.         Note that unlike the Python sys.version, the returned value
  1137.         will always include the patchlevel (it defaults to 0).
  1138.  
  1139.     '''
  1140.     return tuple(string.split(_sys_version()[1], '.'))
  1141.  
  1142.  
  1143. def python_branch():
  1144.     ''' Returns a string identifying the Python implementation
  1145.         branch.
  1146.  
  1147.         For CPython this is the Subversion branch from which the
  1148.         Python binary was built.
  1149.  
  1150.         If not available, an empty string is returned.
  1151.  
  1152.     '''
  1153.     return _sys_version()[2]
  1154.  
  1155.  
  1156. def python_revision():
  1157.     ''' Returns a string identifying the Python implementation
  1158.         revision.
  1159.  
  1160.         For CPython this is the Subversion revision from which the
  1161.         Python binary was built.
  1162.  
  1163.         If not available, an empty string is returned.
  1164.  
  1165.     '''
  1166.     return _sys_version()[3]
  1167.  
  1168.  
  1169. def python_build():
  1170.     ''' Returns a tuple (buildno, builddate) stating the Python
  1171.         build number and date as strings.
  1172.  
  1173.     '''
  1174.     return _sys_version()[4:6]
  1175.  
  1176.  
  1177. def python_compiler():
  1178.     ''' Returns a string identifying the compiler used for compiling
  1179.         Python.
  1180.  
  1181.     '''
  1182.     return _sys_version()[6]
  1183.  
  1184. _platform_cache = { }
  1185.  
  1186. def platform(aliased = 0, terse = 0):
  1187.     ''' Returns a single string identifying the underlying platform
  1188.         with as much useful information as possible (but no more :).
  1189.  
  1190.         The output is intended to be human readable rather than
  1191.         machine parseable. It may look different on different
  1192.         platforms and this is intended.
  1193.  
  1194.         If "aliased" is true, the function will use aliases for
  1195.         various platforms that report system names which differ from
  1196.         their common names, e.g. SunOS will be reported as
  1197.         Solaris. The system_alias() function is used to implement
  1198.         this.
  1199.  
  1200.         Setting terse to true causes the function to return only the
  1201.         absolute minimum information needed to identify the platform.
  1202.  
  1203.     '''
  1204.     result = _platform_cache.get((aliased, terse), None)
  1205.     if result is not None:
  1206.         return result
  1207.     (system, node, release, version, machine, processor) = uname()
  1208.     if machine == processor:
  1209.         processor = ''
  1210.     
  1211.     if aliased:
  1212.         (system, release, version) = system_alias(system, release, version)
  1213.     
  1214.     if system == 'Windows':
  1215.         (rel, vers, csd, ptype) = win32_ver(version)
  1216.         if terse:
  1217.             platform = _platform(system, release)
  1218.         else:
  1219.             platform = _platform(system, release, version, csd)
  1220.     elif system in ('Linux',):
  1221.         (distname, distversion, distid) = dist('')
  1222.         if distname and not terse:
  1223.             platform = _platform(system, release, machine, processor, 'with', distname, distversion, distid)
  1224.         else:
  1225.             (libcname, libcversion) = libc_ver(sys.executable)
  1226.             platform = _platform(system, release, machine, processor, 'with', libcname + libcversion)
  1227.     elif system == 'Java':
  1228.         (os_name, os_version, os_arch) = (r, v, vminfo)
  1229.         if terse or not os_name:
  1230.             platform = _platform(system, release, version)
  1231.         else:
  1232.             platform = _platform(system, release, version, 'on', os_name, os_version, os_arch)
  1233.     elif system == 'MacOS':
  1234.         if terse:
  1235.             platform = _platform(system, release)
  1236.         else:
  1237.             platform = _platform(system, release, machine)
  1238.     elif terse:
  1239.         platform = _platform(system, release)
  1240.     else:
  1241.         (bits, linkage) = architecture(sys.executable)
  1242.         platform = _platform(system, release, machine, processor, bits, linkage)
  1243.     _platform_cache[(aliased, terse)] = platform
  1244.     return platform
  1245.  
  1246. if __name__ == '__main__':
  1247.     if not 'terse' in sys.argv:
  1248.         pass
  1249.     terse = '--terse' in sys.argv
  1250.     if 'nonaliased' not in sys.argv:
  1251.         pass
  1252.     aliased = '--nonaliased' not in sys.argv
  1253.     print platform(aliased, terse)
  1254.     sys.exit(0)
  1255.  
  1256.